<template>
  <div class="unit-page">
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" label-width="80px">
        <el-form-item label="单位">
          <el-input v-model="searchForm.keyword" placeholder="请输入单位名称/编号" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.state" placeholder="请选择" clearable style="width: 160px">
            <el-option label="启用" :value="1" />
            <el-option label="停用" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作者">
          <el-input v-model="searchForm.operator" placeholder="请输入" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 260px" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="action-card">
      <el-button type="primary" @click="openDialog">新增</el-button>
      <el-button type="danger" :disabled="multipleSelection.length === 0" @click="handleBatchDelete">
        删除
      </el-button>
      <el-button @click="handleImport">导入</el-button>
      <el-button @click="handleExport">导出</el-button>
    </el-card>

    <el-card class="table-card">
      <el-table :data="tableData" row-key="unitId" style="width: 100%" v-loading="loading" height="520px"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="unitCode" label="单位编号" width="160" />
        <el-table-column prop="unitName" label="单位名称" width="160" />
        <el-table-column prop="unitOrderBy" label="排序" width="80" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.unitState === 1 ? 'success' : 'danger'">
              {{ row.unitState === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="unitDesc" label="备注" min-width="180" show-overflow-tooltip />
        <el-table-column prop="updater" label="操作人" width="140">
          <template #default="{ row }">
            {{ row.updater || row.createor || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.updateTime || row.createrTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="160">
          <template #default="{ row }">
            <el-button type="primary" link @click="() => openDialog(row)">编辑</el-button>
            <el-button type="danger" link @click="() => handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div class="pagination-wrapper">
      <el-pagination v-model:current-page="pageinfo.pageIndex" v-model:page-size="pageinfo.pageSize"
        :page-sizes="[10, 20, 30, 50]" :total="pageinfo.total" background
        layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 右侧抽屉：新增 / 编辑单位 -->
    <el-drawer v-model="dialog.visible" :title="dialog.isEdit ? '编辑' : '新增'" direction="rtl" size="32%">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="单位编号" prop="unitCode">
          <el-input v-model="form.unitCode" placeholder="自动获取系统编号" readonly class="form-input">
            <template #append>
              <el-button @click="generateUnitCode" :loading="generatingCode">自动生成</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="单位名称" prop="unitName">
          <el-input v-model="form.unitName" placeholder="请输入单位名称" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.unitOrderBy" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="unitState">
          <el-radio-group v-model="form.unitState">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="2">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.unitDesc" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="drawer-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import dayjs from 'dayjs'
import myaxios from '@/http/MyAxios'

const searchForm = reactive({
  keyword: '',
  state: null as null | number,
  operator: '',
  dateRange: [] as string[] | []
})

const pageinfo = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

const tableData = ref<any[]>([])
const loading = ref(false)
const multipleSelection = ref<any[]>([])

const formRef = ref<FormInstance>()
const dialog = reactive({
  visible: false,
  isEdit: false
})
const generatingCode = ref(false)

const form = reactive({
  unitId: null as number | null,
  unitCode: '',
  unitName: '',
  unitOrderBy: 0,
  unitState: 1,
  unitDesc: ''
})

const rules: FormRules = {
  unitName: [{ required: true, message: '请输入单位名称', trigger: 'blur' }],
  unitState: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const formatDate = (val?: string | Date | null) => {
  if (!val) return '-'
  return dayjs(val).format('YYYY-MM-DD HH:mm:ss')
}

const getDateParams = () => {
  if (!searchForm.dateRange || searchForm.dateRange.length !== 2) {
    return { startTime: '', endTime: '' }
  }
  return {
    startTime: `${searchForm.dateRange[0]} 00:00:00`,
    endTime: `${searchForm.dateRange[1]} 23:59:59`
  }
}

const getUnitList = () => {
  loading.value = true
  const { startTime, endTime } = getDateParams()
  myaxios({
    url: '/api/Unit/GetUnitPage',
    method: 'get',
    params: {
      Pageindex: pageinfo.pageIndex,
      PageSize: pageinfo.pageSize,
      keyword: searchForm.keyword,
      state: searchForm.state,
      operator: searchForm.operator,
      startTime,
      endTime
    }
  })
    .then(res => {
      const data = res.data?.data
      tableData.value = data?.data || []
      pageinfo.total = data?.listCount || 0
    })
    .catch(() => {
      ElMessage.error('获取单位列表失败')
    })
    .finally(() => {
      loading.value = false
    })
}

const handleSearch = () => {
  pageinfo.pageIndex = 1
  getUnitList()
}

const handleReset = () => {
  searchForm.keyword = ''
  searchForm.state = null
  searchForm.operator = ''
  searchForm.dateRange = []
  pageinfo.pageIndex = 1
  getUnitList()
}

const handleSelectionChange = (selection: any[]) => {
  multipleSelection.value = selection
}

const handleSizeChange = (val: number) => {
  pageinfo.pageSize = val
  pageinfo.pageIndex = 1
  getUnitList()
}

const handleCurrentChange = (val: number) => {
  pageinfo.pageIndex = val
  getUnitList()
}

const resetForm = () => {
  form.unitId = null
  form.unitCode = ''
  form.unitName = ''
  form.unitOrderBy = 0
  form.unitState = 1
  form.unitDesc = ''
  formRef.value?.clearValidate()
}

const openDialog = (row?: any) => {
  resetForm()
  
  // 检查 row 是否是有效的数据对象（不是事件对象）
  // 如果 row 是 PointerEvent 或其他事件对象，则视为新增模式
  const isValidRow = row && 
    typeof row === 'object' && 
    !(row instanceof Event) && 
    !(row instanceof PointerEvent) &&
    (row.unitId !== undefined || row.UnitId !== undefined)
  
  if (isValidRow) {
    dialog.isEdit = true
    // 支持 camelCase 和 PascalCase 两种字段名格式
    const unitId = row.unitId || row.UnitId
    const unitCode = row.unitCode || row.UnitCode
    const unitName = row.unitName || row.UnitName
    const unitOrderBy = row.unitOrderBy || row.UnitOrderBy
    const unitState = row.unitState || row.UnitState
    const unitDesc = row.unitDesc || row.UnitDesc
    
    // 确保 unitId 被正确转换为数字类型
    const unitIdNum = unitId ? Number(unitId) : null
    if (!unitIdNum || unitIdNum === 0 || isNaN(unitIdNum)) {
      console.error('错误：行数据中 unitId 无效', row)
      ElMessage.error('无法获取单位ID，请刷新页面后重试')
      dialog.visible = true
      dialog.isEdit = false
      return
    }
    
    form.unitId = unitIdNum
    form.unitCode = unitCode || ''
    form.unitName = unitName || ''
    form.unitOrderBy = unitOrderBy || 0
    form.unitState = unitState || 1
    form.unitDesc = unitDesc || ''
    
    console.log('编辑单位，unitId:', form.unitId, '原始数据:', row)
  } else {
    dialog.isEdit = false
    if (row && (row instanceof Event || row instanceof PointerEvent)) {
      console.warn('警告：openDialog 接收到事件对象而非行数据，已切换为新增模式')
    }
  }
  dialog.visible = true
}

//添加
const handleSave = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return
  
  // 编辑模式下，检查 unitId 是否存在
  if (dialog.isEdit) {
    const unitIdNum = form.unitId ? Number(form.unitId) : 0
    if (!form.unitId || unitIdNum === 0 || isNaN(unitIdNum)) {
      console.error('编辑模式 unitId 无效:', form.unitId)
      ElMessage.error('单位ID不能为空，请重新打开编辑窗口')
      return
    }
  }
  
  // 新增模式下，确保生成单位编号
  if (!dialog.isEdit && !form.unitCode) {
    await generateUnitCode()
    if (!form.unitCode) {
      ElMessage.warning('请先生成单位编号')
      return
    }
  }
  
  // 准备发送的数据
  let submitData: any
  if (dialog.isEdit) {
    // 编辑模式：确保 unitId 是数字类型且不为 0
    const unitIdNum = Number(form.unitId)
    if (isNaN(unitIdNum) || unitIdNum === 0) {
      ElMessage.error('单位ID无效')
      return
    }
    submitData = {
      unitId: unitIdNum,
      unitCode: form.unitCode || '',
      unitName: form.unitName || '',
      unitOrderBy: form.unitOrderBy || 0,
      unitState: form.unitState || 1,
      unitDesc: form.unitDesc || ''
    }
    console.log('编辑模式，发送的数据:', submitData, '原始 form:', form)
  } else {
    // 新增模式：不发送 unitId（后端会自动生成）
    const { unitId, ...rest } = form
    submitData = rest
    console.log('新增模式，发送的数据:', submitData)
  }
  
  const url = dialog.isEdit ? '/api/Unit/UpdateUnit' : '/api/Unit/CreateUnit'
  myaxios({
    url,
    method: 'post',
    data: submitData
  })
    .then(res => {
      if (res.data?.code === 200) {
        ElMessage.success(res.data?.message || '保存成功')
        dialog.visible = false
        getUnitList()
      } else {
        ElMessage.error(res.data?.message || '保存失败')
      }
    })
    .catch((err) => {
      console.error('保存失败:', err)
      console.error('请求URL:', url)
      console.error('请求数据:', submitData)
      console.error('响应数据:', err?.response?.data)
      
      // 显示详细的错误信息
      let errorMsg = '保存失败'
      if (err?.response?.data) {
        if (err.response.data.message) {
          errorMsg = err.response.data.message
        } else if (err.response.data.errors) {
          // 处理验证错误
          const errors = err.response.data.errors
          const errorMessages = Object.keys(errors).map(key => {
            const messages = Array.isArray(errors[key]) ? errors[key] : [errors[key]]
            return `${key}: ${messages.join(', ')}`
          }).join('; ')
          errorMsg = `验证失败: ${errorMessages}`
        }
      } else if (err?.message) {
        errorMsg = err.message
      }
      ElMessage.error(errorMsg)
    })
}

//单个删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该单位吗？', '提示', { type: 'warning' })
    .then(() =>
      myaxios({
        url: '/api/Unit/DeleteUnit',
        method: 'delete',
        params: { unitId: row.unitId }
      })
    )
    .then(res => {
      if (!res) return
      if (res.data?.code === 200) {
        ElMessage.success(res.data?.message || '删除成功')
        getUnitList()
      } else {
        ElMessage.error(res.data?.message || '删除失败')
      }
    })
    .catch(() => { })
}

//批量删除
const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的单位')
    return
  }
  const ids = multipleSelection.value.map(item => item.unitId)
  ElMessageBox.confirm(`确认删除选中的 ${ids.length} 条记录吗？`, '提示', { type: 'warning' })
    .then(() =>
      myaxios({
        url: '/api/Unit/DeleteUnits',
        method: 'post',
        data: { ids }
      })
    )
    .then(res => {
      if (!res) return
      if (res.data?.code === 200) {
        ElMessage.success(res.data?.message || '删除成功')
        getUnitList()
      } else {
        ElMessage.error(res.data?.message || '删除失败')
      }
    })
    .catch(() => { })
}

const handleImport = () => {
  ElMessage.info('导入功能开发中')
}

//导出
const handleExport = () => {
  const { startTime, endTime } = getDateParams()
  myaxios({
    url: '/api/Unit/ExportUnit',
    method: 'get',
    params: {
      keyword: searchForm.keyword,
      state: searchForm.state,
      operator: searchForm.operator,
      startTime,
      endTime
    },
    responseType: 'blob'
  })
    .then(res => {
      const blob = new Blob(
        [res.data],
        { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }
      )
      const disposition =
        (res as any).headers?.['content-disposition'] || (res as any).headers?.get?.('content-disposition')
      let filename = '单位列表.xlsx'
      if (disposition && disposition.includes('filename')) {
        const match = /filename\*=UTF-8''([^;]+)|filename=([^;]+)/i.exec(disposition)
        filename = decodeURIComponent((match?.[1] || match?.[2] || filename).replace(/\"/g, '').trim())
      }
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = filename
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(link.href)
      ElMessage.success('导出成功')
    })
    .catch(() => {
      ElMessage.error('导出失败')
    })
}

onMounted(() => {
  getUnitList()
})

const TIME_SEGMENT_ORDER = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
const pad = (n: number, len = 2) => `${n}`.padStart(len, '0')

const buildCodeFromRule = (rule: any) => {
  const now = new Date()
  const segments = (rule?.timeRule || '')
    .split(',')
    .map((s: string) => s.trim().toUpperCase())
    .filter(Boolean)
    .sort((a: string, b: string) => {
      const indexA = TIME_SEGMENT_ORDER.indexOf(a)
      const indexB = TIME_SEGMENT_ORDER.indexOf(b)
      if (indexA === -1 && indexB === -1) return 0
      if (indexA === -1) return 1
      if (indexB === -1) return -1
      return indexA - indexB
    })
  const datePart = segments
    .map((seg: string) => {
      switch (seg) {
        case 'YYYY': return String(now.getFullYear())
        case 'YY': return String(now.getFullYear()).slice(-2)
        case 'MM': return pad(now.getMonth() + 1)
        case 'DD': return pad(now.getDate())
        case 'HH': return pad(now.getHours())
        case 'MI': return pad(now.getMinutes())
        case 'SS': return pad(now.getSeconds())
        default: return ''
      }
    })
    .join('')
  const seq = '1'.padStart(rule?.serialLength || 3, '0')
  return `${rule?.codePrefix || ''}${datePart}${seq}`
}

const requestUnitCode = async () => {
  try {
    const res = await myaxios.get('/api/Number/GenerateNumber', {
      params: { targetCode: 'Unit', targetName: '单位' }
    })
    if (res?.data?.code === 200 && res?.data?.data) {
      return String(res.data.data)
    }
    throw new Error(res?.data?.message || '生成编号失败')
  } catch (err) {
    console.warn('[unit] GenerateNumber 接口不可用，尝试规则生成', err)
    const ruleRes = await myaxios.get('/api/Number/QueryNumberingRules', {
      params: { targetCode: 'Unit', targetName: '单位' }
    })
    const list = Array.isArray(ruleRes?.data?.data) ? ruleRes.data.data : []
    if (list.length > 0) {
      return buildCodeFromRule(list[0])
    }
    throw new Error('未找到对应的编号规则，请先配置编号规则')
  }
}

const generateUnitCode = async () => {
  generatingCode.value = true
  try {
    form.unitCode = await requestUnitCode()
    ElMessage.success('编号生成成功')
  } catch (err: any) {
    ElMessage.error(err?.message || '生成编号失败')
  } finally {
    generatingCode.value = false
  }
}
</script>

<style scoped>
.unit-page {
  padding: 10px;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 15px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
}

.drawer-footer {
  text-align: right;
}

:deep(.form-input) {
  width: 400px !important;
}

:deep(.form-input .el-input__wrapper) {
  width: 100% !important;
}
</style>
